package casa.depesos.app.com.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import casa.depesos.app.com.BuildConfig;
import casa.depesos.app.com.R;
import casa.depesos.app.com.databinding.ActivityCardBinding;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.CameraTipDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.CardInfoBean;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.data.CardInfo;
import casa.depesos.app.com.http.data.UploadType;
import casa.depesos.app.com.http.req.CardInfoReq;
import casa.depesos.app.com.http.req.UploadReq;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class CardActivity extends BaseActivity {

    ActivityCardBinding binding;
    boolean showTip = false;
    HashMap<String, String> set = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCardBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.top.top.setPadding(0, Utils.getStatusBarHeight(this), 0, 0);
        binding.top.title.setText("Verificación de identidad");
        binding.top.back.setOnClickListener(view -> dealBack());
        binding.front.setOnClickListener(view -> showTip(true));
        binding.cardBack.setOnClickListener(view -> showTip(false));
        Report.show("ACTION_LL_001");
        binding.next.setOnClickListener(v -> {
            jump();
        });

        showLoading();
        new CardInfoReq(false).req(new ReqCallback<CardInfoBean>() {
            @Override
            public void callback(boolean success, CardInfoBean bean) {
                hideLoading();
                if (success && bean.isValid() && !Constant.white) {
                    if (!TextUtils.isEmpty(bean.card.front)) {
                        check(true, true, bean.card.front);
                        Glide.with(binding.front).load(bean.card.front).placeholder(R.mipmap.card_front).into(binding.front);
                    }
                    if (!TextUtils.isEmpty(bean.card.back)) {
                        check(true, false, bean.card.back);
                        Glide.with(binding.cardBack).load(bean.card.back).placeholder(R.mipmap.card_back).into(binding.cardBack);
                    }
                }
            }
        });
    }

    private void showTip(boolean front) {
        if (front) {
            Report.click(binding.frontErr.getVisibility() == View.VISIBLE ? "ACTION_LL_005" : "ACTION_LL_003");
        } else {
            Report.click(binding.backErr.getVisibility() == View.VISIBLE ? "ACTION_LL_006" : "ACTION_LL_004");
        }
        if (showTip) {
            toCamera(front);
        } else {
            new CameraTipDlg().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    showTip = true;
                    toCamera(front);
                }
            }).show(getSupportFragmentManager(), "");
        }
    }

    private void toCamera(boolean front) {
        if (Utils.hasPermission(this, Manifest.permission.CAMERA)) {
            Intent i = new Intent(CardActivity.this, CameraCardActivity.class);
            i.putExtra("front", front);
            startActivityForResult(i, 10);
        } else {
            Report.show("ACTION_LL_007");
            XXPermissions.with(this).permission(Permission.CAMERA).request(new OnPermissionCallback() {
                boolean deal = false;

                @Override
                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                    if (allGranted) {
                        Report.click("ACTION_LL_008");
                        Intent i = new Intent(CardActivity.this, CameraCardActivity.class);
                        i.putExtra("front", front);
                        startActivityForResult(i, 10);
                    } else {
                        onDenied(false);
                    }
                }

                @Override
                public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                    onDenied(doNotAskAgain);
                }

                void onDenied(boolean doNotAskAgain) {
                    if (deal) {
                        return;
                    }
                    deal = true;
                    Report.click("ACTION_LL_009");
                    if (doNotAskAgain) {
                        showDlg();
                    }
                }
            });
        }
    }

    ArrayList<String> paths = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == RESULT_OK) {
            String p = data.getStringExtra("path");
            paths.add(p);
            boolean front = data.getBooleanExtra("front", true);
            if (front) {
//                if (BuildConfig.DEBUG) {
//                    p = new File(Environment.getExternalStorageDirectory(), "front.jpg").getAbsolutePath();
//                }
                binding.frontErr.setVisibility(View.GONE);
                binding.frontCover.setImageResource(R.mipmap.camera);
            } else {
//                if (BuildConfig.DEBUG) {
//                    p = new File(Environment.getExternalStorageDirectory(), "back.jpg").getAbsolutePath();
//                }
                binding.backErr.setVisibility(View.GONE);
                binding.backCover.setImageResource(R.mipmap.camera);
            }
            Glide.with(this).load(new File(p)).addListener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    if (front) {
                        binding.front.setImageDrawable(resource);
                    } else {
                        binding.cardBack.setImageDrawable(resource);
                    }
                    return true;
                }
            }).preload();
            showLoading();
            final String path = p;
            new UploadReq(front ? UploadType.ID_FRONT : UploadType.ID_BACK, p).req(new ReqCallback<GetCodeBean>() {
                @Override
                public void callback(boolean success, GetCodeBean bean) {
                    if (success && bean.isValid() || Constant.white) {
                        check(true, front, path);
                    } else {
                        hideLoading();
                        if (front) {
                            binding.frontCover.setImageDrawable(new ColorDrawable(0x88000000));
                            binding.frontErr.setVisibility(View.VISIBLE);
                        } else {
                            binding.backCover.setImageDrawable(new ColorDrawable(0xcc000000));
                            binding.backErr.setVisibility(View.VISIBLE);
                        }
                        check(false, front, null);
                    }
                }
            });
        }
    }

    private void check(boolean success, boolean front, String path) {
        if (success) {
            if (front) {
                binding.front.setEnabled(false);
                set.put("front", path);
            } else {
                binding.cardBack.setEnabled(false);
                set.put("back", path);
            }
            if (set.size() != 2) {
                hideLoading();
            }
        } else {
            if (front) {
                set.remove("front");
            } else {
                set.remove("back");
            }
        }
        if (set.size() == 2) {
            new CardInfoReq(false).req(new ReqCallback<CardInfoBean>() {
                @Override
                public void callback(boolean success, CardInfoBean bean) {
                    hideLoading();
                    if (success && bean.isValid()) {
                        cardInfo = bean.card;
                    }
                    binding.next.setAlpha(1f);
                    binding.next.setEnabled(true);
                    jump();
                }
            });
        } else {
            binding.next.setAlpha(0.6f);
            binding.next.setEnabled(false);
        }
    }

    CardInfo cardInfo = null;

    private void jump() {
        if (cardInfo == null) {
            new CardInfoReq(false).req(new ReqCallback<CardInfoBean>() {
                @Override
                public void callback(boolean success, CardInfoBean bean) {
                    hideLoading();
                    if (success && bean.isValid()) {
                        cardInfo = bean.card;
                        toNext(false);
                    }
                }
            });
        } else {
            toNext(false);
        }
    }

    private void toNext(boolean direct) {
        Intent i = new Intent(CardActivity.this, CardSureActivity.class);
        if (TextUtils.isEmpty(cardInfo.front)) {
            cardInfo.front = set.get("front");
        }
        if (TextUtils.isEmpty(cardInfo.back)) {
            cardInfo.back = set.get("back");
        }
        i.putExtra("card", cardInfo);
        i.putExtra("direct", direct);
        startActivity(i);
        finish();
    }


    private void showDlg() {
        new AlertDialog.Builder(this, R.style.StackedAlertDialogStyle).setMessage("Asegúrase de que tenga habilitados los permisos de la cámara. Si no lo ha hecho, actívalos en Configuración > Permisos. Sin estos permisos, no podrá tomar fotos.")
                .setPositiveButton("Ir a configurar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null);
                        intent.setData(uri);
                        startActivity(intent);
                    }
                }).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create().show();
    }

    @Override
    protected boolean needPadding() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (String p : paths) {
            new File(p).delete();
        }
    }

    @Override
    protected boolean needKeep() {
        return true;
    }
}
